/*
 * @Description: promise回顾
 * @Author: Zhanghan
 * @Date: 2025-03-19 13:43:55
 * @LastEditTime: 2025-03-24 08:53:15
 * @LastEditors: Zhanghan
 */
import { useState } from "react";
import { Button } from "antd";
function Basics() {
  const [flag, setFlag] = useState(true);
  const [str, setStr] = useState<any>();
  // 定义一个返回 Promise 的函数
  const testPromise = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (flag) {
          resolve("数据获取成功");
        } else {
          reject("数据获取失败");
        }
      }, 1500);
    });
  };

  const getData = async () => {
    try {
      const res = await testPromise();
      console.log(res);
      if (res) {
        setStr(res);
      }
    } catch (err) {
      console.log(err);
    } finally {
      setFlag(!flag);
    }
  };

  return (
    <>
      <div>
        <div className="mb-2">MyPromise基础</div>
        <div className="mb-2">{str ?? "点击获取数据"}</div>
        <div>
          <Button type="primary" onClick={getData}>
            获取数据
          </Button>
        </div>
      </div>
    </>
  );
}

export default Basics;
